package com.lizk.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;



/**
 * 重入锁对中断的处理，使用“lock.lockInterruptibly()”的方式加锁可以响应线程的中断处理，响应的方式为抛出异常，可以捕获异常以后做一些处理，但是如果没有手工解锁的话，依然不会释放资源
 * @author lizk
 *
 */
public class ReentrantLockTest {
	ReentrantLock lock = new ReentrantLock();
	
	Runnable r = new Runnable(){
		@Override
		public void run() {
			try {
				lock.lockInterruptibly();
				System.out.println(Thread.currentThread().getName() + "获取锁");
				System.out.println(Thread.currentThread().getName() + "执行开始");
				TimeUnit.SECONDS.sleep(2);
				System.out.println(Thread.currentThread().getName() + "执行结束");
			} catch (InterruptedException e) {
				System.out.println(Thread.currentThread().getName() + "被中断");
				try {
					System.out.println(Thread.currentThread().getName() + "中断等待");
					TimeUnit.SECONDS.sleep(2);
					System.out.println(Thread.currentThread().getName() + "中断结束");
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}finally {
				
				//虽然终端使加锁抛出异常，但是如果不解锁，依然不释放资源
				lock.unlock();
				System.out.println(Thread.currentThread().getName() + "释放锁");
			}
		}
		
	};
	
	public static void main(String[] args) {
		ReentrantLockTest test = new ReentrantLockTest();
		Thread t1 = new Thread(test.r,"t1");
		Thread t2 = new Thread(test.r,"t1");
		t1.start();
		t2.start();
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t1.interrupt();
		
		
	}
}
